package com.xg.common.util;


import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * 工具类判断空和其他各种方法
 */
public class Func {

    public static Boolean isNull(Object o){
        return null == o;
    }

    public static Boolean notNull(Object o){
        return null != o;
    }

    public static Boolean isEmpty(Object o){
        if (o == null) {
            return true;
        } else if(o instanceof String){
            return "".equals(o);
        } else if (o instanceof List) {
            return CollectionUtils.isEmpty((List)o);
        } else {
            return false;
        }
    }


    public static Object copyProperties(Object sourceBean, Object targetBean){
        BeanUtils.copyProperties(sourceBean, targetBean);
        return targetBean;
    }

    /**
     * 只能转换同属性名，且相同类型的字段，基础类型与其对象类型也可
     * @param sourceBean
     * @param t
     * @param <T>
     * @return
     */
    public static <T>T copyProperties(Object sourceBean, Class<T> t){
        T targetBean = null;
        try {
            targetBean = t.newInstance();
            BeanUtils.copyProperties(sourceBean, targetBean);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return targetBean;
    }


    /**
     * 获取百分比
     * @param dividend
     * @param divisor
     * @return
     */
    public static String getRate(BigDecimal dividend, BigDecimal divisor){
        double val = dividend.divide(divisor, 3, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).doubleValue();
        return val == 0. ? "0" : (val + "%");
    }

    /**
     * 数字转字符串，指定位数，前补0
     * @return
     */
    public static String numberFormatStr(Integer number, Integer digit){
        StringBuilder f = new StringBuilder("0");
        for(int i=1; i<digit; i++){
            f.append("0");
        }
        DecimalFormat format = new DecimalFormat(f.toString());
        return format.format(number);
    }

    /**
     * 属性去重
     * @param keyExtractor
     * @param <T>
     * @return
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return object -> seen.putIfAbsent(keyExtractor.apply(object), Boolean.TRUE) == null;
    }
}
